<?php
/**
 * Created by PhpStorm.
 * User: sogubaby
 * Date: 2019-02-22
 * Time: 14:15
 */

namespace Service;

use App\Models\UserBankCard;
use App\Models\UserLoanRequest;

trait User {
    /**
     * 融360用户银行卡
     * @param $userId
     * @return array
     * @author luwei
     * @date 2019-02-22 15:21
     */
    public function userBankList($userId) {
        $userBankCard = UserBankCard::where('uid', $userId)
            ->orderBy('id', 'desc')
            ->get();

        $bankInfo = [];
        foreach ($userBankCard as $bank) {
            if ($bank->is_credit == UserBankCard::CREDIT_YES) {
                $cardType = 2;
            } else {
                $cardType = 1;
            }
            $bankInfo[] = [
                'open_bank'     => $bank->getOriginal('bank_code'),
                'bank_card'     => $bank->card_num,
                'card_type'     => $cardType,
                'is_repay_card' => 1,
            ];
        }
        return $bankInfo;
    }

    /**
     * 360订单号转用户信息
     * @param $orderNo
     * @return \App\Models\User|array|mixed
     * @author luwei
     * @date 2019-03-01 10:06
     */
    public function orderNoToUser($orderNo){
        $loan = UserLoanRequest::with(['user'])->byTransId($orderNo)->first();
        if($loan && $loan->user){
            return $loan->user;
        }else{
            return [];
        }
    }


    /**
     * 返回还款计划表中的还款卡 参考
     * @param $orderNo
     * @return bool
     * @author luwei
     * @date 2019-03-01 13:54
     */
    public function getRepayBankCard($orderNo){
        $user = $this->orderNoToUser($orderNo);
        //获取用户最后一次借款的数据
        $repaySummary = self::where('uid',$user->id)
            ->with(['recordOne'=>function($q){
                $q->where('status','<>',RepayRecord::STATUS_FOUR);
                $q->where('pay_off','=',RepayRecord::PAY_OFF_TWO);
            },'recordOne.money','recordOne.month','recordOne.common'])
            ->orderBy('id','desc')
            ->first();
        if(!isset($repaySummary->recordOne)){
            $repaySummary = self::where('uid',$user->id)
                ->with(['recordOne'=>function($q){
                    $q->where('status','<>',RepayRecord::STATUS_FOUR);
                    $q->where('pay_off','=',RepayRecord::PAY_OFF_ONE);
                },'recordOne.money','recordOne.month','recordOne.common'])
                ->orderBy('id','desc')
                ->first();
            return $repaySummary->recordOne->bank_cards_id;
        }
        return false;
    }
}